package com.itheima.blog.util;

import com.itheima.blog.util.constants.Constants;

import java.util.HashMap;
import java.util.Map;

/**
 * 存放用户id的容器
 */
public class UserThreadLocalUtils {

    private final static ThreadLocal<Map<Integer, Integer>> userThreadLocal = new ThreadLocal<>(){
        @Override
        protected Map<Integer, Integer> initialValue() {
            return new HashMap<>(4);
        }
    };

    /**
     * 获取线程中的admin用户
     *
     * @return
     */
    public static Integer getAdminUserId() {
        Map<Integer, Integer> map = userThreadLocal.get();
        return map.get(Constants.USER_TYPE_ADMIN);
    }

    /**
     * 获取线程中的web用户
     *
     * @return
     */
    public static Integer getWebUserId() {
        Map<Integer, Integer> map = userThreadLocal.get();
        return map.get(Constants.USER_TYPE_WEB);
    }

    /**
     * 设置当前线程中的admin用户
     *
     * @param userId
     */
    public static void setAdminUserId(Integer userId) {
        Map<Integer, Integer> map = userThreadLocal.get();
        map.put(Constants.USER_TYPE_ADMIN, userId);
    }

    /**
     * 设置当前线程中的web用户
     *
     * @param userId
     */
    public static void setWebUserId(Integer userId) {
        Map<Integer, Integer> map = userThreadLocal.get();
        map.put(Constants.USER_TYPE_WEB, userId);
    }

    /**
     * 判断admin用户是否已经登录
     * */
    public static boolean isAdminUserLogin(){
        Integer adminUserId = getAdminUserId();
        return adminUserId != null && adminUserId > 0;
    }

    /**
     * 判断web用户是否已经登录
     * */
    public static boolean isWebUserLogin(){
        Integer webUserId = getWebUserId();
        return webUserId != null && webUserId > 0;
    }

    public static void removeUser(){userThreadLocal.remove();}

}
